import 'package:flutter/material.dart';
import 'package:flutter_nest_life/utils/TokenManager.dart';

import '../utils/EventBus.dart';
import 'home/index.dart';
import 'mine/index.dart';

class TabsPage extends StatefulWidget {
  const TabsPage({super.key});

  @override
  _TabsPageState createState() => _TabsPageState();
}

class _TabsPageState extends State<TabsPage> {
  // 底部tabbar List
  final List _tabbarList = [
    {
      'label': '首页',
      'icon': 'assets/tabs/home_default.png',
      'activeIcon': 'assets/tabs/home_active.png',
    },
    {
      'label': '我的',
      'icon': 'assets/tabs/my_default.png',
      'activeIcon': 'assets/tabs/my_active.png',
    }
  ];

  // 底部tabbar 当前选中的index
  int _currentIndex = 0;

  updateCurrentIndex(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  // // 第一种方案 --> 通过index来判断显示哪个页面
  // // 明确返回类型为 Widget，并添加默认返回值
  // Widget getTabbarContent() {
  //   if (_currentIndex == 0) {
  //     return const HomePage();
  //   } else if (_currentIndex == 1) {
  //     return MinePage(currentIndex: _currentIndex);
  //   }
  //   return const SizedBox.shrink();
  // }
  // 第二种方案 -> (性能更优) IndexStacked -> 通过index 指定渲染 (不会每次都销毁重建)

  // 封装 获取底部TabsItem 内容
  List<BottomNavigationBarItem> getBottomNavigationBarItems() {
    List<BottomNavigationBarItem> list = [];
    for (var item in _tabbarList) {
      list.add(BottomNavigationBarItem(
          icon: Image.asset(item['icon'], width: 30, height: 30),
          label: item['label'],
          activeIcon: Image.asset(item['icon'], width: 30, height: 30)));
    }
    return list;
  }

  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    // 初始化token
    _initToken();
    // 订阅消息 LogoutEvent
    registerLogoutEvent();
  }

  Future<void> _initToken() async {
    try {
      await tokenManager.init();
    } catch (e) {
      // 处理初始化失败的情况
      print('Token 初始化失败: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  registerLogoutEvent() {
    eventBus.on<LogoutEvent>().listen((event) {
      if (event.forceLogout) {
        // 仅处理强制登出事件
        Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false);
      }
    });
  }

  Future<bool> _onWillPop() async {
    return await showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('确认退出'),
            content: const Text('您确定要退出应用吗？'),
            actions: <Widget>[
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () => Navigator.of(context).pop(true),
                child: const Text('确定'),
              ),
            ],
          ),
        ) ??
        false;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        // SafeArea 安全区组件
        body: SafeArea(
          child: IndexedStack(
            index: _currentIndex,
            children: [
              const HomePage(),
              MinePage(
                  currentIndex: _currentIndex,
                  updateCurrentIndex: updateCurrentIndex)
            ],
          ),
        ),
        // 底部的tabbar TODO
        bottomNavigationBar: BottomNavigationBar(
            type: BottomNavigationBarType.fixed,
            currentIndex: _currentIndex,
            selectedItemColor: const Color.fromRGBO(99, 144, 174, 1),
            unselectedItemColor: Colors.black,
            items: getBottomNavigationBarItems(),
            onTap: (int index) {
              setState(() {
                _currentIndex = index;
              });
            }),
      ),
    );
  }
}
